import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter_douban/config/Http_service.dart';
import 'package:flutter_douban/config/app_colors.dart';
import 'package:flutter_douban/config/app_config.dart';
import 'package:flutter_douban/config/event_bus_util.dart';
import 'package:flutter_douban/config/sqflite/cook_db_provider.dart';
import 'package:flutter_douban/loading/custom_footer.dart';
import 'package:flutter_douban/loading/custom_header.dart';
import 'package:flutter_douban/main_page/collect/view/cook_item_cell.dart';
import 'package:flutter_douban/model/cook_info_model.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:shared_preferences/shared_preferences.dart';

import 'attention_view.dart';
import 'cook_image_page.dart';

class HomeAttentionPage extends StatefulWidget {
  const HomeAttentionPage({Key? key}) : super(key: key);

  @override
  _HomeAttentionPageState createState() => _HomeAttentionPageState();
}

class _HomeAttentionPageState extends State<HomeAttentionPage> with AutomaticKeepAliveClientMixin {
  // 下拉刷新控制器
  EasyRefreshController? _easyRefreshController;
  // 独立的滚动视图 防止tab切换时触发下拉刷新
  ScrollController? _scrollController;
  // 列表数组模型
  List<CookInfoModel> _cookInfoList = CookInfoModelList([]).list;
  StreamSubscription<CacheCookEvent>? _cacheCookSubscription;
  StreamSubscription<LoginEvent>? _loginSubscription;

  @override
  void initState() {
    super.initState();
    _easyRefreshController = EasyRefreshController();
    _scrollController = ScrollController();
    _loginSubscription = EventBusUtil.listen((event) {
      setState(() {
        getData();
      });
    });
    _cacheCookSubscription = EventBusUtil.listen((event) {
      setState(() {
        getData();
      });
    });
  }

  @override
  void dispose() {
    _easyRefreshController!.dispose();
    _scrollController!.dispose();
    super.dispose();
  }

  Future<void> getData() async {
    CookDbProvider provider = new CookDbProvider();
    SharedPreferences prefs = await SharedPreferences.getInstance();
    String? numberId = prefs.getString(AppConfig.numberId);
    if(numberId == null){
      numberId = '123';
    }
    List<CookInfoModel> list = [];
    provider.getAllClassInfo(numberId).then((value) => {
      list = value,
      setState(() {
        _cookInfoList = list;
      }),
    });
  }


  @override
  Widget build(BuildContext context) {
    return EasyRefresh(
      // 开启首次加载刷新
      firstRefresh: true,
      header: CustomHeaderView(),
      footer: CustomFooterView(),
      controller: _easyRefreshController,
      enableControlFinishRefresh: false,
      enableControlFinishLoad: true,
      onRefresh: getData,
      child: CustomScrollView(
        slivers: <Widget>[
          // 如果不是Sliver家族的Widget，需要使用SliverToBoxAdapter做层包裹
          SliverToBoxAdapter(
            child: Container(
              height: 105,
              color: AppColors.line,
              child: _headerView(),
            ),
          ),
          // 当列表项高度固定时，使用 SliverFixedExtendList 比 SliverList 具有更高的性能
          SliverList(
            delegate: SliverChildBuilderDelegate(
              (context, index) => AttentionView(model: _cookInfoList[index]),
              childCount: _cookInfoList.length,
            ),
          ),
        ],
      ),
    );
  }

  @override
  bool get wantKeepAlive => true;

  Widget _headerView (){
    return Container(
      alignment: Alignment.topLeft,
      margin: EdgeInsets.only(left: 20,top: 20),
      child: Column(
        mainAxisAlignment: MainAxisAlignment.start,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            '豆果美食,会做饭很酷~',
            overflow: TextOverflow.ellipsis,
            style: TextStyle(
              fontSize: 15,
              fontWeight: FontWeight.bold,
              color: AppColors.black,
            ),
          ),
          SizedBox(height: 10,),
          Text(
            '你关注人的动态会出现在这',
            overflow: TextOverflow.ellipsis,
            style: TextStyle(
              fontSize: 12,
              color: AppColors.qianTextColor,
            ),
          ),
          SizedBox(height: 2,),
          Text(
            '为你推荐了一些有趣的人,快去关注TA们吧',
            overflow: TextOverflow.ellipsis,
            style: TextStyle(
              fontSize: 12,
              color: AppColors.qianTextColor,
            ),
          ),
        ],
      ),
    );
  }
}
